
SControllers.controller('index_ctrl', ['$scope', '$http', '$timeout',
  function($scope, $http, $timeout) {
      
      var spiderServerHost = "";
      chrome.storage.local.get("spiderServerHost", function(data) {
          spiderServerHost = data.spiderServerHost;
          $scope.load_crawl_list(1, 10);
      });

      var dataServerHost = "";
      chrome.storage.local.get("dataServerHost", function(data) {
          dataServerHost = data.dataServerHost;
      });
      
      var port = chrome.runtime.connect({name:"router_proxy"});
      port.postMessage({method:"init"});
      
      $scope.close = function() {
          port.postMessage({method:"close"});
      };

      $scope.minimize = function() {
          var current_window = chrome.app.window.current();
          current_window.minimize();
      };

      $scope.crawl_list = [];
      $scope.config = {};
      $scope.keys = [];
      $scope.current_field = {"id":Math.uuid(8, 16), "datatype":"string", "ismultiple":true};
      $scope.crawlName = "";
      $scope.stepID = "";
      $scope.currentStep = {};
      $scope.currentCrawl = {};

      $("#index").show();
      $("#step").hide();
      $("#extract_config").hide();

      var applyTimer;
      $scope.safeApply = function(fn) {
          var phase = $scope.$root.$$phase;
          if (phase == '$apply' || phase == '$digest') {
              applyTimer = $timeout(function() {$scope.safeApply(fn)}, 5); 
          } else {
              $scope.$apply();
              if (typeof (fn) === "function") {
                  fn();
              }
          }
      }

      $scope.load_crawl_list = function(pageno, perpage) {
          var url = "http://"+spiderServerHost+"/spiderkit/flowcrawl_list?pageno="+pageno+"&perpage="+perpage;
          $http.get(url).success(
            function(data) {
                $scope.crawl_list = data;
                $scope.currentCrawl = {};
                $scope.safeApply();
            }
          );
      };

      $scope.to_index = function(target) {
          $scope.load_crawl_list(1, 10);
          $("#index").show();
          $("#step").hide();
          $("#extract_config").hide();
      };

      $scope.crawl_step_select_onclick = function(target) {
          $scope.crawlName = target.getAttribute("data-name");
          for (var i = 0; i < $scope.crawl_list.length; i ++) {
              if ($scope.crawl_list[i]["name"] === $scope.crawlName) {
                  $scope.currentCrawl = $scope.crawl_list[i];
                  break;
              }
          }

          $scope.to_step_select();
      }

      $scope.to_step_select = function() {
          $("#index").hide();
          $("#step").show();
          $("#extract_config").hide();
      }
       
      $scope.to_extract_config = function(target) {
          $scope.stepID = target.getAttribute("data-sid");

          for(var i = 0; i < $scope.currentCrawl["steps"].length; i ++) {
              if ($scope.currentCrawl["steps"][i]["stepID"] == $scope.stepID) {
                  $scope.currentStep = $scope.currentCrawl["steps"][i];
                  break;
              }
          }

          var url = "http://"+spiderServerHost+"/spiderkit/flowcrawl_extract_get?pluginName="+$scope.crawlName+"&stepID="+$scope.stepID;
          $http.get(url).success(
            function(data){
                if (data.length === 0) {
                    $scope.config = {"name":$scope.crawlName, "stepID":$scope.stepID, "fields":[]};
                } else {
                    $scope.config = data[0];
                }
                $scope.keys = [];
                $("#need_pick_tips").show();
                $("#index").hide();
                $("#step").hide();
                $("#extract_config").show();
            }
          );
      };

      
      $scope.dataTypes = [{
          id:1,
          type :'string',
      }, {
          id:2,
          type :'int',
      }, {
          id:3,
          type :'float',
      }, {
          id:4,
          type :'double',
      }];

      
      $("#need_pick_tips").show();
      $("#save-requesting-tips").hide(); 
      $("#save-success-tips").hide(); 
      $("#save-failed-tips").hide(); 
      $("#extract-requesting-tips").hide(); 
      $("#extract-success-tips").hide(); 
      $("#extract-running-tips").hide(); 
      $("#extract-failed-tips").hide(); 

      var router = new tcpRouter();
      router.addRouter("/", function(req){
          return "Welecome !";
      });

      router.addRouter("/elementPath", function(req){
          $scope.keys = JSON.parse(decodeURIComponent(req.parms.keys));

          if ($scope.keys.length > 0) {
              $("#need_pick_tips").hide();
          }

          $scope.safeApply();
          return "success";
      });
      
      router.addRouter("/system/close", function(req){
          var current_window = chrome.app.window.current();
          current_window.close();
      });

      router.addRouter("/serServerHost", function(req){
          spiderServerHost = req.parms.spiderServerHost;
          dataServerHost = req.parms.dataServerHost;

          if (spiderServerHost !== undefined) {
              chrome.storage.local.set({"spiderServerHost":spiderServerHost});
              console.log("set spiderServerHost " + spiderServerHost);
              $scope.load_crawl_list(1, 10);
          }

          if (dataServerHost !== undefined) {
              chrome.storage.local.set({"dataServerHost":dataServerHost});
              console.log("set dataServerHost " + dataServerHost);
          }

          return "success";
      });
 
      
      port.onMessage.addListener(function(msg){
          port.postMessage({response: router.getRouter(msg.request.path)(msg.request)});
      });

      $scope.add_field = function() {
          if ($scope.keys.length === 0)
              return;
          if ($scope.current_field["key"] === undefined || $scope.current_field["key"] === "")
              return;
          $scope.current_field["keys"] = $scope.keys;
          $scope.config["fields"].push($scope.current_field);
          $scope.keys = [];
          $scope.current_field = {"id":Math.uuid(8, 16), "datatype":"string", "ismultiple":true};
      };
      
      $scope.delete_field = function(target) {
        var id = target.id;
        for ( var i = 0; i < $scope.config["fields"].length; i ++) {
            if ($scope.config["fields"][i]["id"] === id) {
                $scope.config["fields"].splice(i, 1);
                return;
            }
        }
      };
      
      $scope.save_config = function() {
          var configstr = encodeURIComponent(angular.toJson($scope.config));
          var url = "http://"+spiderServerHost+"/spiderkit/flowcrawl_extract_save?pluginName="+$scope.crawlName+"&stepID="+$scope.stepID+"&config="+configstr;
          $("#save-requesting-tips").show(); 
          $http.get(url).success(
            function(data) {
                $("#save-requesting-tips").hide(); 
                if (data === "success") {
                    $("#save-success-tips").show(); 
                    $timeout(function() {$("#save-success-tips").hide()}, 1000);
                } else {
                    $("#save-failed-tips").show(); 
                    $timeout(function() {$("#save-failed-tips").hide()}, 1000);
                }
            }
          ).error(function(){
                $("#save-requesting-tips").hide(); 
          });
      };
      
      $scope.extract_data = function() {
          var url = "http://"+dataServerHost+"/DBServer/TestServer?type=select&step_id="+$scope.stepID+"&rc_name="+$scope.currentCrawl['name'];
          $("#extract-requesting-tips").show(); 
          $http.get(url).success(
            function(data) {
                $("#extract-requesting-tips").hide();
                if (data === "1") {
                    $("#extract-success-tips").show(); 
                    $timeout(function() {$("#extract-success-tips").hide()}, 1000);
                } else if (data === "0") {
                    $("#extract-running-tips").show(); 
                    $timeout(function() {$("#extract-running-tips").hide()}, 1000);
                } else {
                    $("#extract-failed-tips").show(); 
                    $timeout(function() {$("#extract-failed-tips").hide()}, 1000);
                }
            }
          ).error(function(){
                $("#extract-requesting-tips").hide();
          });
      }
      
      $scope.extract_test_url = "";
      $scope.extract_test_data = function() {
          var testurl = encodeURIComponent($scope.extract_test_url);
          var url = "http://"+dataServerHost+"/DBServer/TestServer?type=test&step_id="+$scope.stepID+"&rc_name="+$scope.currentCrawl['name']+"&url="+testurl;
          $("#extract-requesting-tips").show(); 
          $http.get(url).success(
            function(data) {
                console.log(data);
                $("#extract-requesting-tips").hide();
                showMessage(data);
            }
          ).error(function(){
                $("#extract-requesting-tips").hide();
          });
      };

      var message_modal_show = false;
      $('#messageModal').on('show.bs.modal', function (e) {
          message_modal_show = true;
      });

      $('#messageModal').on('hide.bs.modal', function (e) {
          message_modal_show = false;
      });

      function showMessage(text) {
          $('#message').html(text);
          if (!message_modal_show) {
              $('#messageModal').modal({keyboard: false});
          }
      }

  }]
);


